package com.pucong.gitee.database.backup.business.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pucong.gitee.database.backup.business.sys.service.GetLogFileContentService;
import com.pucong.gitee.database.backup.common.entity.sys.vo.LogFileListVo;
import com.pucong.gitee.database.backup.common.entity.sys.vo.WebSocketReturnVo;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import com.pucong.gitee.database.backup.utils.ApplicationContextUtil;
import com.pucong.gitee.database.backup.utils.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


@Slf4j
@ServerEndpoint(value = "/websocket/logfile")
@Component
public class WebSocketLogFile {
    /**
     * 记录当前在线连接数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        onlineCount.incrementAndGet(); // 在线数加1
        clients.put(session.getId(), session);
        log.info("有新连接加入：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        clients.remove(session.getId());
        log.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        ThreadPoolUtils.executor(() -> {
            ObjectMapper objectMapper = new ObjectMapper();
            LogFileListVo logFileVo = null;
            try {
                logFileVo = objectMapper.readValue(message, LogFileListVo.class);
            } catch (IOException e) {
                log.error("Json转换异常");
                log.error("异常信息:{}", e);
                throw new BusinessException("传入参数错误");
            }
            GetLogFileContentService systemLogFileService = (GetLogFileContentService) ApplicationContextUtil.getBean(GetLogFileContentService.class);
            WebSocketReturnVo logFile = systemLogFileService.getLogFile(logFileVo.getLogFileName(), logFileVo.getStartLine(), logFileVo.getMaxLine());
            String resStr = "";
            try {
                resStr = objectMapper.writeValueAsString(logFile);
            } catch (IOException e) {
                log.error("Json转换异常");
                log.error("异常信息:{}", e);
                throw new BusinessException("Json转换异常");
            }
            sendMessage(session.getId(), resStr);
        });
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误", error);
        error.printStackTrace();
    }

    /**
     * 群发消息
     *
     * @param message 消息内容
     */
    private void sendMessage(String sessionId, String message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            if (sessionId.equals(toSession.getId())) {
                toSession.getAsyncRemote().sendText(message);
            }
        }
    }
}
